import { _decorator, RigidBody, Vec3 ,Node, SkeletalAnimation, input, Input, EventKeyboard, KeyCode, Collider, ITriggerEvent} from 'cc';
import { GameUnit } from './GameUnit';
import { GameWorld } from '../GameWorld';
import { Edible } from './Edible';
const { ccclass, property } = _decorator;

@ccclass('Slime')
export class Slime extends GameUnit {
    @property
    public speed: number = 1.0;
    private rigidBody: RigidBody = null;

    @property({type : Node})
    public Mesh : Node = null;

    @property({type : SkeletalAnimation})
    public Animation : SkeletalAnimation = null;

    private _collider : Collider = null;

    private readonly _tempVec3 : Vec3 = new Vec3();

    protected onLoad(): void {
        this.rigidBody = this.node.getComponent(RigidBody);
        this._collider = this.getComponent(Collider);
        this._collider.on('onTriggerEnter', this.onTriggerEnter, this);
    }


    private runaniState : boolean = false;

    start() {

    }

    protected onDestroy(): void {

    }

    update(deltaTime: number) {
        this.rigidBody.getLinearVelocity(this._tempVec3);
        if(this._tempVec3.length() > 0.01 && !this.runaniState) {
            this.Animation.crossFade("Run",0.1);
            this.runaniState = true;
        }
        if(this._tempVec3.length() <= 0.01 && this.runaniState) {
            this.Animation.crossFade("Idel",0.3);
            this.runaniState = false;
        }
    }

    protected lateUpdate(dt: number): void {
        
    }

    public Move(dir: Vec3): void {
        if(dir.x != 0 || dir.y != 0 || dir.z != 0) {
            dir = dir.multiply3f(this.speed, this.speed, this.speed);
            this.rigidBody.setLinearVelocity(dir);
            this.Mesh.lookAt(this.node.getPosition().subtract(dir));
        } 
    }

    private onTriggerEnter (event: ITriggerEvent) {
        let edible = event.otherCollider.getComponent(Edible);
        if(edible && edible.node.scale.x <= this.node.scale.x) {
            edible.node.active = false;
            let s = edible.node.scale.x * 0.02 + this.node.scale.x;
            this.node.setScale(s,s,s);
        }
    }
}


